package com.education.webservlet;

import com.education.db.HibernateSessionFactory;
import com.education.db.dao.InfoUserDAO;
import com.education.db.domain.InfoUser;
import com.education.util.Constant;
import com.education.util.MD5Util;
import org.hibernate.Transaction;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by Fan307 on 2016/11/7.
 */
@WebServlet(name = "UserRegServlet")
public class UserRegServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private Transaction tran;

    public UserRegServlet() {

        super();
    }
    public void destroy() {
        super.destroy();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding(Constant.CHAR_ENCODING);

        tran = HibernateSessionFactory.getSession().getTransaction();

        String datetime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Calendar.getInstance().getTime());
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        password = MD5Util.MD5(password);

        try {
            tran.begin();
            InfoUserDAO infoUserDAO = new InfoUserDAO();
            InfoUser infoUser = (InfoUser) infoUserDAO.findByUsPhone(phone);
            if (infoUser != null) {
                String info=String.format( "用户已存在，2秒后为您自动跳到登录页面！！<meta http-equiv='refresh' content='2;url=%s'", request.getContextPath()+"/user/UserLogin.jsp");
                request.setAttribute("info", info);
                request.getRequestDispatcher("/Pages/message.jsp").forward(request,
                        response);
            } else {
                infoUser = new InfoUser();
                infoUser.setUsPhone(phone);
                infoUser.setUsType((byte) 1);
                infoUser.setUsRegdate(Timestamp.valueOf(datetime));
                infoUser.setUsPassword(password);
                infoUserDAO.save(infoUser);
                String info=String.format( "注册成功，2秒后为您自动跳到登录页面！！<meta http-equiv='refresh' content='2;url=%s'", request.getContextPath()+"/user/UserLogin.jsp");
                request.setAttribute("info", info);
                request.getRequestDispatcher("/Pages/message.jsp").forward(request,
                        response);
            }
            tran.commit();
        } catch (Exception e) {
            System.out.println(e.toString());
            tran.rollback();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
